package com.tanhua.dubbo.async;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.MovementTimeLine;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 异步线程
     */
    @Async
    public void saveTimeline(Long loginUserId, ObjectId movementId, Long timeMillis){
        log.debug("进入了异常线程处理：添加好友时间线记录");
        // 构建查询条件
        Query friendQuery = new Query(Criteria.where("userId").is(loginUserId));
        List<Friend> friends = mongoTemplate.find(friendQuery, Friend.class);
        //TODO 好友有1000+ 如何解决? 最好的方案是由MQ来做
        if(CollectionUtil.isNotEmpty(friends)){
            for (Friend friend : friends) {
                MovementTimeLine timeLine = new MovementTimeLine();
                timeLine.setMovementId(movementId);
                timeLine.setUserId(loginUserId);
                // 【注意】不能使用getUserId=loginUserId
                timeLine.setFriendId(friend.getFriendId());
                timeLine.setCreated(timeMillis);
                mongoTemplate.insert(timeLine);
            }
        }
    }
}
